package com.mdd.common.util;
import javax.imageio.ImageIO;
import com.google.zxing.*;
import java.awt.image.BufferedImage;
import java.io.File;
import com.google.zxing.common.BitMatrix;
import com.mdd.common.util.oss.OSSStsUtil;

import java.util.HashMap;
import java.util.Map;

public class QrCode {

	//生成二维码颜色
		private static final int BLACK = 0xFF000000;
		//生成二维码颜色
		private static final int WHITE = 0xFFFFFFFF;

		/**
		 * 	生成二维码
		 * @param text    二维码内容
		 * @param width    二维码宽
		 * @param height    二维码高
		 * @param outPutPath    二维码生成保存路径
		 * @param imageType     二维码生成格式
		 */
		public static String codeCreate(String text){
			String payPath = "";
			long start = System.currentTimeMillis();
			System.out.println("开始生成时间："+start);
			Map<EncodeHintType, String> his = new HashMap<EncodeHintType, String>();
			//设置编码字符集
			his.put(EncodeHintType.CHARACTER_SET, "utf-8");
			try {
				//生成二维码
				BitMatrix encode = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, 500, 500, his);
				//获取到二维码宽高
				int codeWidth = encode.getWidth();
				int codeHeight = encode.getHeight();
				//将二维码放入缓冲流中
				BufferedImage image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);
				for (int i = 0; i < codeWidth; i++) {
					for (int j = 0; j < codeHeight; j++) {
						//循环将二维码内容套入图片
						image.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);
					}
				}
				String payPathDev = OSSStsUtil.getPayPath(".png");
				File outPutImage = new File(payPathDev);
				if(outPutImage.mkdirs()) {
					//如果图片不存在创建图片
					if(!outPutImage.exists()) {
						outPutImage.createNewFile();
					}
					//将二维码写入图片
					ImageIO.write(image, "png", outPutImage);
					// 将图片存入oss
					payPath = OSSStsUtil.uploadLocalFile(payPathDev);
				}
				// https://kdkdkd.oss-cn-shanghai.aliyuncs.com
				return "https://kdkdkd.oss-cn-shanghai.aliyuncs.com/"+payPath;
			} catch (Exception e) {
				e.printStackTrace();
				payPath = "";
			}
			return payPath;
		}

		public static void main(String[] args) {
			String codeCreate = codeCreate("http://192.168.0.150:8080/api/v1/order/qryOrder");
			System.out.println("cc:"+codeCreate);
		}
}
